<template>
    <div class="flex-container" :style="{ height: clientHeight + 'px' }">
        <div class="title">给PDF文件添加水印</div>
        <el-upload
            ref="upload"
            drag
            :limit="1"
            action="-"
            :auto-upload="false"
            accept=".pdf"
            :show-file-list="false"
            :on-change="onChange"
        >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <div style="width: 360px; margin: 25px 0px">
            <el-input v-model="watermarkText" clearable placeholder="请输入文本"></el-input>
        </div>
        <el-button type="primary" @click="handleBack" size="medium" round>返回主页</el-button>
    </div>
</template>

<script>
import { degrees, PDFDocument, rgb } from 'pdf-lib'
import fontkit from '@pdf-lib/fontkit'
import saveAs from 'file-saver'
export default {
    data() {
        return {
            clientHeight: document.documentElement.clientHeight || document.body.clientHeight,
            watermarkText: '',
            filename: ''
        }
    },
    methods: {
        async handleData(arrayBuffer) {
            const pdfDoc = await PDFDocument.load(arrayBuffer)
            const pages = pdfDoc.getPages()
            pdfDoc.registerFontkit(fontkit)
            var defaultFontBuffer = await fetch('/fonts/SourceHanSansCN-Light.otf').then(res => res.arrayBuffer())
            const helveticaFont = await pdfDoc.embedFont(defaultFontBuffer)
            pages.forEach(page => {
                const { width, height } = page.getSize()
                page.drawText(this.watermarkText, {
                    x: width / 2 - (this.watermarkText.length * 30)/2,
                    y: height / 2 - (this.watermarkText.length * 40)/2,
                    size: 50,
                    font: helveticaFont,
                    color: rgb(0.75, 0.75, 0.75),
                    rotate: degrees(45),
                    opacity: 0.5
                })
            })
            const pdfBytes = await pdfDoc.save()
            let blob = new Blob([pdfBytes])
            saveAs(blob, this.filename + '_watermark.pdf')
        },
        onChange(file) {
            this.filename = file.name.split('.')[0]
            let pattern = /.(pdf)$/g
            if (!pattern.test(file.name)) {
                this.$message.error('只能上传pdf文件')
                return false
            }
            if (!this.watermarkText) {
                this.$message.error('请输入文本')
                return false
            }
            let load = this.$loading({
                lock: true,
                text: '正在导出...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            })
            const reader = new FileReader()
            let that = this
            reader.onload = function (event) {
                const arrayBuffer = event.target.result
                that.handleData(arrayBuffer)
            }
            reader.readAsArrayBuffer(file.raw)
            this.$refs.upload.clearFiles()
            load.close()
            return true
        },
        handleBack() {
            this.$router.replace('/')
        }
    }
}
</script>

<style scoped>
.flex-container {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}
.el-button--primary {
    background-color: #505587;
    border-color: #505587;
}
.el-upload-dragger .el-upload__text em {
    color: #505587;
}
.title {
    font-size: 24px;
    line-height: 34px;
    color: #33333b;
    font-weight: 600;
    margin-bottom: 25px;
}
</style>
